package cn.yunhe.controller;

import cn.yunhe.model.*;
import cn.yunhe.service.UserGuanliService;
import cn.yunhe.utils.EmailUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/yonghu1")
public class YonghuguanliAction1 {

    @Resource
    private UserGuanliService userGuanli;
    @RequestMapping("/tomember-list")
    public ModelAndView queryUsers(){
        ModelAndView mv = new ModelAndView();
        List<Users> userdlist = userGuanli.queryUsers();
        System.out.println(userdlist.get(1).getU_bir());
        mv.addObject("userlist",userdlist);
        mv.setViewName("member-list");
        return mv;
    }

    @RequestMapping("/tocar-list")
    public ModelAndView tocarlist(){
        ModelAndView mv = new ModelAndView();
        List<Cars> carslist = userGuanli.queryCars();
        mv.addObject("carslist",carslist);
        mv.setViewName("car-list");
        return mv;
    }

    @RequestMapping("/tomember-del")
    public ModelAndView querydongjieUsers(){
        ModelAndView mv = new ModelAndView();
        List<Users> userdlist = userGuanli.querydongjieUsers();
        /*System.out.println(userdlist.get(1).getU_bir());*/
        mv.addObject("userlist",userdlist);
        mv.setViewName("member-del");
        return mv;
    }


    @RequestMapping("/tomember-ting")
    public ModelAndView queryUsers(Users user,HttpSession session){
        ModelAndView mv = new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行用户停用操作");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("修改");//(添加，删除，修改)
        UserNumber usenum = (UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(usenum.getUn_id());                  //session中的当前用户id

        ma.put("blog",blog);
        ma.put("users",user);
        int flag = userGuanli.edittingyonguser(ma);
        mv.addObject("flag",flag);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    @RequestMapping("/tomember-qi")
    public ModelAndView edithuanyuanuser(Users user,HttpSession session){
        ModelAndView mv = new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行用户还原操作");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("修改");//(添加，删除，修改)
        UserNumber usenum = (UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(usenum.getUn_id());                  //session中的当前用户id

        ma.put("blog",blog);
        ma.put("users",user);
        int flag = userGuanli.edithuanyuanuser(ma);
        System.out.println(11111111);
        mv.addObject("flag",flag);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    @RequestMapping("/editcar")
    public ModelAndView editcar(Cars car,HttpSession session){
        ModelAndView mv = new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行车牌修改");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("修改");//(添加，删除，修改)
        UserNumber usenum = (UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(usenum.getUn_id());                  //session中的当前用户id

        ma.put("blog",blog);
        ma.put("car",car);
        int flag = userGuanli.queryCarsid(car.getC_id());
        System.out.println(flag);
        if(flag==1){
            mv.addObject("flag","修改失败！该车牌已存在");
        }else{
            try{
                flag = userGuanli.editCarsid(ma);
                mv.addObject("flag","修改成功！");
                mv.addObject("c_id",car.getC_color());
            }catch(Exception e){
               // e.printStackTrace();
                System.out.println("出错了");
                mv.addObject("flag","该车已经购买保险，请先退保！");
            }finally {
                System.out.println("==="+car.getC_id()+"125");
                //mv.setView(new MappingJackson2JsonView());
                mv.setViewName("car-edit");
                return mv;
            }
        }
        return mv;

    }
    @RequestMapping("/delcar")
    public ModelAndView delcar(@RequestBody List<String> c_id,HttpSession session){
        ModelAndView mv = new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("删除"+c_id.size()+"辆车");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("删除");//(添加，删除，修改)
        UserNumber usenum = (UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(usenum.getUn_id());                  //session中的当前用户id

        ma.put("blog",blog);

        ma.put("car",c_id);
        System.out.println(c_id.size()+"456789");

            int flag = userGuanli.delCarsid(ma);


            mv.addObject("flag",flag);
        mv.setView(new MappingJackson2JsonView());

        return mv;
    }
    @InitBinder("time")
    public void initDate(WebDataBinder webDataBinder){
        webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }


    @RequestMapping("/adduser")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    public ModelAndView addUsers(Users user,Date time,HttpSession session) throws ParseException {
        ModelAndView mv = new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行用户添加操作");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("添加");//(添加，删除，修改)
        UserNumber usenum = (UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(usenum.getUn_id());                  //session中的当前用户id

        System.out.println();
        user.setU_bir(time);
        user.setUn_id(1);//session中的当前用户id

        UserNumber usern = new UserNumber();
        String card = user.getU_idcard();
        usern.setUsername(card.substring(6,18));

        //ByteSource
        ByteSource salt = ByteSource.Util.bytes(card.substring(6,18));
        //将密码加密
        SimpleHash sh = new SimpleHash("MD5",card.substring(6,18),salt,1024);
        System.out.println(sh);
        String password = sh.toString();

        usern.setPassword(password);
        usern.setUn_nickname("默认昵称");
        usern.setUn_pwdsalt(user.getU_phone());
        //System.out.println(usern.getUsername());
        ma.put("blog",blog);
        ma.put("usern",usern);
        ma.put("users",user);
        int u_id = userGuanli.adduser(ma);
      /*  int flag = userGuanli.editUsers(ma);*/


        user.setU_id(u_id);       //把主键set到users对象里
        usern.setUsers(user);   //把users对象set到账号对象里
        int flag = userGuanli.usernum(usern);
        EmailUtil emal = new EmailUtil();
        emal.send_qqmail(user.getU_emal(), "【安康保险】", "<body><p>尊敬的用户您好，你已成功成为安康保险的用户，您的初始账号为："+card.substring(6,18)+"，初始密码为："+card.substring(6,18)+"，祝您生活愉快！</p></body>");
        mv.addObject("flag","添加成功");
        System.out.println(user.getU_remark()+"+"+time+"***"+flag);
     /*   mv.addObject("flag",flag);*/
        mv.setViewName("member-add");
        System.out.println("5555k");
        return mv;
    }


    @RequestMapping("/jianyanidcard")
    public ModelAndView jianyan(Users user){
        ModelAndView mv = new ModelAndView();
        String id_card = user.getU_idcard();
        int flag = userGuanli.queryUser(id_card);
        mv.addObject("flag",flag);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }


    @RequestMapping("/touseredit")
    public ModelAndView editUsers1(Users user,HttpSession session){
        ModelAndView mv = new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行用户详细信息的修改操作");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("修改");//(添加，删除，修改)
        UserNumber usenum = (UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(usenum.getUn_id());                  //session中的当前用户id

        ma.put("blog",blog);
        ma.put("users",user);
        int flag = userGuanli.editUsers(ma);
        System.out.println(user.getU_id());
        mv.addObject("flag",flag);
        mv.setViewName("user-edit");
        System.out.println("kkkkkkkk");
        return mv;
    }

    @RequestMapping("/jianyanuser")
    public ModelAndView jianyanuser(Users user){
        ModelAndView mv = new ModelAndView();
        Integer u_id = userGuanli.queryUserid(user);
        System.out.println("1111111"+u_id);
        mv.addObject("flag",u_id);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    @RequestMapping("/jianyancarid")
    public ModelAndView jianyancar(Cars car){
        ModelAndView mv = new ModelAndView();
        int flag = userGuanli.queryCarsid(car.getC_id());
        System.out.println("1111111"+flag);
        mv.addObject("flag",flag);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }


    @RequestMapping("/fileUpload")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    public ModelAndView  fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request, Users users,Cars cars,Date time,HttpSession session) throws IOException {
        ModelAndView mv = new ModelAndView();

        String path1 = request.getServletContext().getRealPath("");//获取项目动态绝对路径
        System.out.println(path1);
        System.out.println(time);

        String filename = file.getOriginalFilename();
        file.getContentType();
        File dest = new File(filename);

        System.out.println(filename);


        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行车辆的添加");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("添加");//(添加，删除，修改)
        UserNumber usenum = (UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(usenum.getUn_id());                  //session中的当前用户id


        ma.put("blog",blog);
        Integer u_id = userGuanli.queryUserid(users);
        if(u_id==null){
            mv.addObject("flag","该用户不存在，请检查");
            System.out.println("该用户不存在，请检查");
        }else{

            cars.setC_buydate(time);//添加出生日期
            cars.setC_pic(filename);//添加图片名称
            cars.setUn_id(1);            //session中的当前用户id
            users.setU_id(u_id);//添加用户id
            cars.setUsers(users);//添加到cars中

            ma.put("cars",cars);
            int flag = userGuanli.addcar(ma);
            mv.addObject("flag","添加成功");
            System.out.println("添加成功");
            if (flag==1){
                try{
                    file.transferTo(dest);
                    System.out.println("上传成功");
                }catch (IllegalStateException | IOException e){
                    System.out.println("上传失败");
                }
            }
        }

        mv.setViewName("car-add");
        return mv;
    }



    public UserGuanliService getUserGuanli() {
        return userGuanli;
    }

    public void setUserGuanli(UserGuanliService userGuanli) {
        this.userGuanli = userGuanli;
    }

}
